"use strict"

var request = require('supertest')
  , cookieParser 	= require('cookie-parser')
  , bodyParser = require("body-parser")
  , express = require('express')
  , should  = require('chai').should
  , expect  = require('chai').expect
  , urlencode = require("urlencode")
  , webRequest = require("request");

//process.env.NODE_ENV = 'local-unit-test';

var redirectUrl;

describe('GET /', function(){
  it('should be redirect to qywx login page', function(done){
    var app = express();
    app.use(cookieParser());
    app.use(bodyParser());

    var qywx = express();
    app.use("/qywx", qywx);

    require('../')(qywx, {});

    request(app)
      .get('/qywx/auth?domain=qywx-admin&client_id=56f6bff4caa511fd56c94d88&corpId=wx42c1a7f89c4a258d&cb=' + urlencode("http://www.baidu.com?state=123"))
      .set('Host', 'auth.aivics.net')
      .expect(302)
      .expect(function(res){
        console.log(res.headers);
        redirectUrl = res.headers['location'];
      })
      .end(done);
  });
});
//
// describe('GET login page', function(){
//   it("should get login page", function(done){
//     var options = {
//       url: redirectUrl,
//       headers: {
//        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
//        'Referer': 'http://auth.aivics.net'
//       }
//     };
//     webRequest(options, function(err, res, body){
//       if(err) {
//         console.log(err)
//         return done(err);
//       }
//       console.log(body);
//       done();
//     });
//   });
// });

var DummyContext = function(){
  if( !(this instanceof DummyContext )){
    return new DummyContext();
  }
}
DummyContext.prototype.get = function(domain, cb){
  return cb(null, {
    clients: ['56f6bff4caa511fd56c94d88']
    ,qywx: {
      corpId: 'wx42c1a7f89c4a258d&cb=',
      corpSecret: 'BrMySu4oO_J2psgOkMKaZ0K6NexnI0pNeOPC9F-L5nARiJqSLYY_7I9NVWL0YGca'
    }
  })
};

describe('GET token', function(){
  it("should get token", function(done){
    var app = express();
    app.use(cookieParser());
    app.use(bodyParser());

    var qywx = express();
    app.use("/qywx", qywx);
    require('../')(qywx, {});

    qywx.locals.context = new DummyContext();

    request(app)
      .get("/qywx/token?auth_code=123&expires_in=600&client_id=56f6bff4caa511fd56c94d88&domain=qywx-admin")
      .set('Host', 'auth.aivics.net')
      .expect(200)
      .expect(function(res){
        console.log(res.headers);
        redirectUrl = res.headers['location'];
      })
      .end(done);
  });
});
